package com.huawei.jenkins.cloudpipeline;

import com.google.common.base.Preconditions;
import com.huaweicloud.sdk.codeartspipeline.v2.CodeArtsPipelineClient;
import com.huaweicloud.sdk.codeartspipeline.v2.model.*;
import com.huaweicloud.sdk.codeartspipeline.v2.region.CodeArtsPipelineRegion;
import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.smn.v2.SmnClient;
import com.huaweicloud.sdk.smn.v2.model.PublishMessageRequest;
import com.huaweicloud.sdk.smn.v2.model.PublishMessageRequestBody;
import com.huaweicloud.sdk.smn.v2.model.PublishMessageResponse;
import com.huaweicloud.sdk.smn.v2.region.SmnRegion;
import hudson.model.TaskListener;
import org.apache.commons.lang.StringUtils;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;


public class CodeArtsPipelineService implements Serializable {
    private static final long serialVersionUID = 1;

    public static String runPipeline(TaskListener listener, CustomInput customInput) {
        inputValidate(customInput);
        ICredential auth = new BasicCredentials()
                .withAk(customInput.getAk())
                .withSk(customInput.getSk());

        CodeArtsPipelineClient client = CodeArtsPipelineClient.newBuilder()
                .withCredential(auth)
                .withRegion(CodeArtsPipelineRegion.valueOf(customInput.getRegion()))
                .build();
        RunPipelineRequest request = new RunPipelineRequest();
        request.withProjectId(customInput.getProject_id());
        request.withPipelineId(customInput.getPipeline_id());
        RunPipelineDTO body = new RunPipelineDTO();
        request.withBody(body);
        String status = "RUNNING";
        ShowPipelineRunDetailResponse info = null;
        try {
            RunPipelineResponse response = client.runPipeline(request);
            while (!status.equals("COMPLETED")&&!status.equals("FAILED")) {
                info = ShowPipelineRunDetail(client, listener, customInput);
                status = info.getStatus();
                try {
                    Thread.currentThread().sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //临时解决方案，因为域名不一样，url是对应上海一的,只在上海一返回链接,后续api会有链接返回
            if("cn-east-3".equals(customInput.getRegion())){
                String url = "https://devcloud."+customInput.getRegion()+".huaweicloud.com/cicd/project/"+customInput.getProject_id()+"/pipeline/detail/" + customInput.getPipeline_id() + "/" + response.getPipelineRunId() + "?v=1";
                listener.getLogger().println("关于具体详情，可前往：" + url + "\n查看");
            }
            //SMN消息通知
            if(StringUtils.isNotBlank(customInput.getTopicUrn())){
                publishMessage(customInput, info, listener,response.getPipelineRunId());
            }
        } catch (ConnectionException e) {
            e.printStackTrace();
        } catch (RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            e.printStackTrace();
            listener.getLogger().println("ErrorMsg：" + e.getErrorMsg());
        }
        return status;
    }


    public static ShowPipelineRunDetailResponse ShowPipelineRunDetail(CodeArtsPipelineClient client, TaskListener listener, CustomInput customInput) {
        ShowPipelineRunDetailRequest request = new ShowPipelineRunDetailRequest();
        request.withProjectId(customInput.getProject_id());
        request.withPipelineId(customInput.getPipeline_id());
        ShowPipelineRunDetailResponse response = null;
        try {
             response = client.showPipelineRunDetail(request);
            listener.getLogger().println("status：" + response.getStatus());
        } catch (ConnectionException e) {
            e.printStackTrace();
        } catch (RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            e.printStackTrace();
            listener.getLogger().println("ErrorMsg：" + e.getErrorMsg());
        }
        return response;
    }

    private static void inputValidate(CustomInput customInput) {
        final String ak = customInput.getAk();
        final String sk = customInput.getSk();
        final String region = customInput.getRegion();
        final String pipelineId= customInput.getPipeline_id();
        final String projectId = customInput.getProject_id();
        Preconditions.checkArgument(StringUtils.isNotBlank(pipelineId), "pipeline Id can not be blank");
        Preconditions.checkArgument(StringUtils.isNotBlank(projectId), "project Id can not be blank");
        Preconditions.checkArgument(StringUtils.isNotBlank(region), "region can not be blank");
        Preconditions.checkArgument(StringUtils.isNotBlank(ak) && StringUtils.isNotBlank(sk), "Ak, Sk can not be blank");
    }



    public static void publishMessage(CustomInput customInput, ShowPipelineRunDetailResponse info, TaskListener listener,String runId) {
        ICredential auth = new BasicCredentials()
                .withAk(customInput.getAk())
                .withSk(customInput.getSk());

        SmnClient client = SmnClient.newBuilder()
                .withCredential(auth)
                .withRegion(SmnRegion.valueOf(customInput.getRegion()))
                .build();
        PublishMessageRequest request = new PublishMessageRequest();
        request.withTopicUrn(customInput.getTopicUrn());
        PublishMessageRequestBody body = new PublishMessageRequestBody();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String url = "https://devcloud."+customInput.getRegion()+".huaweicloud.com/cicd/project/"+customInput.getProject_id()+"/pipeline/detail/" + customInput.getPipeline_id() + "/" + runId + "?v=1";
        String message = "尊敬的华为云用户，您好：\n执行CodeArts pipeline的信息：";
        message+="\nname：" + info.getName();
        message+="\n开始时间：" + sdf.format(new Date(Long.parseLong(String.valueOf(info.getStartTime()))));
        message+="\n结束时间：" + sdf.format(new Date(Long.parseLong(String.valueOf(info.getEndTime()))));
        message+="\n结果：" + info.getStatus();
        //临时解决方案，因为域名不一样，url是对应上海一的,只在上海一返回链接,后续api会有链接返回
        if("cn-east-3".equals(customInput.getRegion())){
            message+="\n链接：" + url;
        }
        body.withMessage(message);
        request.withBody(body);
        try {
            PublishMessageResponse response = client.publishMessage(request);
        } catch (ConnectionException e) {
            e.printStackTrace();
        } catch (RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            e.printStackTrace();
            listener.getLogger().println("SMN服务消息发生失败，错误信息：" + e.getErrorMsg());
        }
    }







}
